﻿using Mes.车间机床.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace Mes.车间机床
{
    public partial class AddWorkshopForm : Form
    {
        private readonly HttpClient _httpClient;
        public AddWorkshopForm()
        {
            InitializeComponent();
            Load += AddWorkshopForm_Load;
            _httpClient = new HttpClient();
        }

        private async void skinButton1_Click(object sender, EventArgs e)
        {
            try
            {
                WorkShopModel workshop = CollectWorkshopData();
                // 使用 System.Text.Json.JsonSerializer.Serialize 的正确方式
                string jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(workshop);
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization =
                       new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    string apiUrl = "https://localhost:7084/api/WorkShop/AddWorkshop";
                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                    HttpResponseMessage response = await client.PostAsync(apiUrl, content);

                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("添加成功！");
                        LoadMachineToolsToGrid();
                    }
                    else
                    {
                        string errorMessage = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"添加失败：{errorMessage}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误：{ex.Message}");
            }
        }

        private void ClearForm()
        {
            textWorkshopCode.Text = "";
            textWorkshopName.Text = "";
            comWorkshopLocation.Text = "";
            textHeader.Text = "";
            textWorkshopPhone.Text = "";
            comStates.SelectedIndex = -1;
            // 清空机床信息（如果有动态控件，需要遍历清空）
        }


        private void btnMachinAdd_Click(object sender, EventArgs e)
        {
            // 获取当前行数，用于生成序号
            dataGridView1.Rows.Add("", "", "", "删除");
        }

        private async Task<List<MachineToolDto>> GetMachineToolsAsync()
        {
            try
            {
                _httpClient.DefaultRequestHeaders.Authorization =
                       new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                string apiUrl = "http://47.99.221.116:8000/workshop/api/Machine/GetMachine";
                HttpResponseMessage response = await _httpClient.GetAsync(apiUrl);

                if (response.IsSuccessStatusCode)
                {
                    string jsonData = await response.Content.ReadAsStringAsync();
                    // 反序列化为 ApiResponse 对象
                    ApiResponse apiResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiResponse>(jsonData);

                    if (apiResponse !=null && apiResponse.Data !=null)
                    {
                        return apiResponse.Data.Datas; // 返回 Datas 字段中的列表
                    }
                    else
                    {
                        MessageBox.Show("返回的数据格式不正确");
                        return new List<MachineToolDto>();
                    }
                }
                else
                {
                    MessageBox.Show($"获取机床数据失败：{response.StatusCode}");
                    return new List<MachineToolDto>();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误：{ex.Message}");
                return new List<MachineToolDto>();
            }
        }

        private async void LoadMachineToolsToGrid()
        {
            try
            {
                List<MachineToolDto> machines = await GetMachineToolsAsync();

                // 清空现有行
                dataGridView1.Rows.Clear();

                // 添加数据行
                foreach (var machine in machines)
                {
                    dataGridView1.Rows.Add(false, machine.MachineToolCode, machine.MachineToolName, machine.MachineToolType);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载机床数据失败: {ex.Message}");
            }
        }


        private List<MachineToolDto> GetMachinesFromGrid()
        {
            List<MachineToolDto> selectedMachines = new List<MachineToolDto>();

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                // 跳过新建行
                if (row.IsNewRow)
                    continue;

                // 获取多选框的值，并处理可能的空值
                bool isChecked = false;
                object cellValue = row.Cells["checkBoxColumn"].Value;
                if (cellValue !=null  && bool.TryParse(cellValue.ToString(), out isChecked))
                {
                    if (isChecked)
                    {
                        MachineToolDto machine = new MachineToolDto
                        {
                            MachineToolCode = row.Cells["MachineToolCode"].Value?.ToString(),
                            MachineToolName = row.Cells["MachineToolName"].Value?.ToString(),
                            MachineToolType = row.Cells["MachineToolType"].Value?.ToString()
                        };

                        selectedMachines.Add(machine);
                    }
                }
                Console.WriteLine($"Row {row.Index}: CheckBox = {isChecked}, MachineToolCode = {row.Cells["MachineToolCode"].Value?.ToString()}");
            }

            return selectedMachines;
        }
        private WorkShopModel CollectWorkshopData()
        {
            List<MachineToolDto> machines = new List<MachineToolDto>();

            // 遍历 DataGridView 的行，只处理选中的行
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.IsNewRow) continue; // 跳过新建行

                // 检查多选框是否选中
                if (row.Cells["checkBoxColumn"].Value != null&&
                    Convert.ToBoolean(row.Cells["checkBoxColumn"].Value))
                {
                    string machineToolCode = row.Cells["MachineToolCode"].Value?.ToString() ?? string.Empty;
                    string machineToolName = row.Cells["MachineToolName"].Value?.ToString() ?? string.Empty;
                    string machineToolType = row.Cells["MachineToolType"].Value?.ToString() ?? string.Empty;

                    if (!string.IsNullOrEmpty(machineToolCode))
                    {
                        machines.Add(new MachineToolDto
                        {
                            MachineToolCode = machineToolCode,
                            MachineToolName = machineToolName,
                            MachineToolType = machineToolType
                        });
                    }
                }
            }

            return new WorkShopModel
            {
                workshopCode = textWorkshopCode.Text,
                workshopName = textWorkshopName.Text,
                workshoplocation = comWorkshopLocation.Text,
                workshopHead = textHeader.Text,
                phone = textWorkshopPhone.Text,
                state = comStates.Text,
                Machine = machines
            };
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.IsCurrentCellDirty)
            {
                dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        private void AddWorkshopForm_Load(object sender, EventArgs e)
        {
            InitializeDataGridView();
            LoadMachineToolsToGrid();
        }
        private void InitializeDataGridView()
        {
            // 初始化 DataGridView 列
            dataGridView1.Columns.Clear();
            DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn()
            {
                HeaderText = "选择",
                Name = "checkBoxColumn",
                Width = 50
            };

            dataGridView1.Columns.Add(checkBoxColumn);

            dataGridView1.Columns.Add("MachineToolCode", "设备编号");
            dataGridView1.Columns.Add("MachineToolName", "设备名称");
            dataGridView1.Columns.Add("MachineToolType", "设备类型");
            DataGridViewButtonColumn btnColumn = new DataGridViewButtonColumn
            {
                Name = "Operation",
                HeaderText = "操作",
                Text = "删除",
                UseColumnTextForButtonValue = true,
                Width = 60
            };
            dataGridView1.Columns.Add(btnColumn);

            // 设置列宽，让数据列填满剩余空间
            int totalWidth = dataGridView1.Width;
            int usedWidth = 50 + 60; // 选择列和操作列的宽度
            int remainingWidth = totalWidth - usedWidth;
            int dataColumnWidth = remainingWidth / 3; // 平均分配给三个数据列
            
            dataGridView1.Columns["MachineToolCode"].Width = dataColumnWidth;
            dataGridView1.Columns["MachineToolName"].Width = dataColumnWidth;
            dataGridView1.Columns["MachineToolType"].Width = dataColumnWidth;
            
            // 设置自动调整列宽
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            dataGridView1.AllowUserToAddRows = false;

            // 禁止用户添加行（可选）
            dataGridView1.AllowUserToAddRows = false;
        }
    }
    
}

